package com.gao.controller;

import commomresult.CommonResult;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import pojo.Payment;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gaofeng
 */
@RestController
@EnableEurekaClient
public class ConsumerController {

    /**
     * 调用支付订单服务端的ip+端口号
     */
    public static final  String PAYMENT_URL = "http://localhost:8001";

    /**
     * Ribbon提供的实现负载均衡的注解
     */
    @Resource
    private RestTemplate restTemplate;
    
    /**
     * springCloud提供的获取元数据的工具类
     *  1. 引入依赖
     *  2. 配置eureka的配置
     *  3. 注入discoveryClient
     */
    @Resource
    private DiscoveryClient discoveryClient ;

    @GetMapping("/consumer/pay/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject("http://mcroservice-payment/pay/queryById/" + id, CommonResult.class);
    }

    /**
     * 1. 创建RestTemplate的时候,声明@LoadBalanced
     * 2. 使用RestTemplate调用远程微服务,请求的服务名替换ip地址
     * @author gaofeng
     * @date  2022/8/18 19:29
     * @param id
     * @return java.util.List<commomresult.CommonResult<pojo.Payment>>
     */
    @GetMapping("/consumer/pay/getPayment/{id}")
    public List<CommonResult<Payment>> getPaymentByRibbon(@PathVariable("id") Long id){
        List<CommonResult<Payment>> products = new ArrayList<>() ;
        List<ServiceInstance> instances = discoveryClient.getInstances("mcroservice-payment");
        for (ServiceInstance instance : instances) {
            products.add(restTemplate.getForObject("http://" + instance.getHost() + ":" + instance.getPort() + "/pay/queryById/" + id, CommonResult.class));
        }
        return products ;
    }

    /**
     * 获取id获取支付订单
     * @param id 主键
     * @return CommonResult
     */
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/pay/queryById/" + id, CommonResult.class);
    }

}
